// JavaScript Document
$(document).ready(function(){
    var resetEvenColor = function(){
        $('tbody tr').removeClass("alt-row");
        $('tbody tr:even').delay(100).addClass("alt-row");
    };
    var _editHrefHandler = function(){
        var objtr = $(this).parents("tr");
        $("#newWebLink").resetForm();
        $("#newWebLink").attr("action", "/action/master/EditWebLink");
        $("#linkid").val($(this).attr("href"));
        $("#name").val(objtr.find("a:first").text());
        $("#url").val(objtr.find("a:first").attr("href"));
        $("#view_logo").html(objtr.find("img").clone());
        $("#logo").val(objtr.find("img").attr("src"));
        return false;
    };
    
    var _newHrefHandler = function(){
        $("#newWebLink").resetForm();
        $("#newWebLink").attr("action", "/action/master/AddWebLink");
        $("#logo").val("");
        $("#view_logo").text("");
        $("#linkid").val(-1);
        $("#name").val("");
        $("#url").val("");
        return false;
    };
    
    var _deleteHrefHandler = function(){
        var tmp = $(this);
        $.post("/action/master/DeleteWebLink", {
            Action: "post",
            id: tmp.attr("href")
        }, function(data, textStatus){
            if (!data.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: data.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: data.message
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                tmp.parent().parent().effect("highlight", {
                    color: "#F00"
                }, 800, function(){
                    $(this).remove();
                    resetEvenColor();
                });
                //$(".notification").removeClass("error").addClass("success").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
            }
        }, "json");
        return false;
    };
    
    var _saveBtnHandler = function(){
        $("#newWebLink").submit();
        return false;
    };
    
    var _insertElement = function(data){
        var template = $("#link-tpl").clone().show();
        template.attr("id", "tr_" + data.temp);
        template.find("a:first").attr("href", $("#url").val()).text($("#name").val());
        template.find("a:eq(1)").attr("href", data.temp).click(_editHrefHandler);
        template.find("a:last").attr("href", data.temp).click(_deleteHrefHandler).easyconfirm({
            locale: {
                title: '操作确认',
                button: ['取消', '是的，确定删除']
            }
        });
        template.find("td:nth-child(2)").html("<img src=\"" + $("#logo").val() + "\" />");
        $("#data-content").append(template);
        resetEvenColor();
    };
    var _updateElement = function(data){
        var tid = $("#linkid").val();
        var updateTR = $("#tr_" + tid);
        updateTR.find("a:first").attr("href", $("#url").val()).text($("#name").val());
        updateTR.find("td:nth-child(2)").html("<img src=\"" + $("#logo").val() + "\" />");
        
        updateTR.effect("highlight", {
            color: "#FF0"
        }, 3000);
    };
    $(".saveBtn").click(_saveBtnHandler);
    $(".editBtn").click(_editHrefHandler);
    $(".deleteBtn").click(_deleteHrefHandler).easyconfirm({
        locale: {
            title: '操作确认',
            button: ['取消', '是的，确定删除']
        }
    });
    $(".newBtn").click(_newHrefHandler);
    
    jQuery.validator.addMethod("stringCheck", function(value, element){
        return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
    }, "只能包括中文字、英文字母、数字和下划线");
    
    // 中文字两个字节       
    jQuery.validator.addMethod("byteRangeLength", function(value, element, param){
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) ||
        (length >= param[0] && length <= param[1]);
    }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");
    
    $("#newWebLink").validate({
        submitHandler: function(form){
            $(form).ajaxSubmit({
                target: "#errormsg",
                dataType: "json",
                beforeSubmit: function(){
                    $(".loadingbox").append(loadingTpl, {
                        icoType: 'clear',
                        loadIcon: '<img src=\"/images/manage/loading002.gif\">',
                        msgHtml: '正在提交数据，请稍候...'
                    });
                    $(".loading").fadeIn(50);
                },
                success: function(data){
                    $("#errormsg").text(data.message);
                    if (!data.success) {
                        //$(".notification").removeClass("success").addClass("error").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: 'fail',
                            loadIcon: '',
                            msgHtml: data.message
                        });
                        $(".loadingbox").delay(3000).fadeOut(600);
                    }
                    else {
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: "succ",
                            loadIcon: "",
                            msgHtml: data.message
                        });
                        $(".loadingbox").fadeIn(50);
                        $(".loadingbox").delay(2000).fadeOut(600);
                        if ($("#linkid").val() == -1) {
                            _insertElement(data);
                        }
                        else {
                            _updateElement(data);
                        }
                        //$(".notification").removeClass("error").addClass("success").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                    }
                    
                }
            });
        },
        rules: {
            name: {
                required: true,
                byteRangeLength: [4, 40],
                stringCheck: true
            },
            url: {
                required: true,
                url: true
            },
            logo: {
                required: true
            }
        
        
        },
        messages: {
            name: {
                required: "请填写单位名称",
                byteRangeLength: "单位名称必须在4-40个字符之间(一个中文字算2个字符)"
            },
            url: {
                required: "请填写链接地址",
                url: "链接地址格式错误，请检查"
            },
            logo: {
                required: "请上传LOGO图片"
            }
        
        }
    });
    
    
    // upload	
    var uploader = '../js-plugin/uploadify/uploadify_cn.swf';
    var images_script = "/action/master/WebLinkLogoUpload";
    var cancelImg = '../js-plugin/uploadify/cancel.png';
    var folder = '/upload';
    
    
    $('#logo_upload').uploadify({
        'uploader': uploader,
        'script': images_script,
        'cancelImg': cancelImg,
        'folder': folder,
        'auto': true,
        'fileExt': '*.jpg;*.gif;*.png;*.bmp',
        'fileDesc': '请选择图片文件 (.JPG, .GIF, .PNG, .BMP)',
        'queueID': 'custom-queue',
        'buttonText': "选择上传图片",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            var obj = $.parseJSON(response);
            if (obj.success) {
				alert(1);
                $('#logo').val(obj.filepath);
                $("#view_logo").text("").append("<img src=\"" + obj.filepath + "\" />");
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: obj.message
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(3000).fadeOut(600);
            }
        }
        
    });
})
